import json
import re

from django.contrib.auth import login, authenticate, logout
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection

from qiniu import Auth
from qiniu import etag
from qiniu import put_file,put_data

from ihome.utils import constants

from homes.models import House
from ihome.utils.image_storage import storage

from utils.views import LoginRequiredJSONMixin
from users.models import User

# 注册用户
class RegisterView(View):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        phonecode = json_dict.get('phonecode')

        # 必要性校验
        if not all([mobile,password,phonecode]):
            return JsonResponse({'errno':400,'errmsg':'缺少参数'})

        if not re.match('^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\\d{8}$',mobile):
            return JsonResponse({'errno': 400, 'errmsg': '手机号格式有误'})

        # 判断短信验证码是否正确
        conn = get_redis_connection("verify_code")
        redis_phonecode = conn.get("sms_%s" % mobile)
        if redis_phonecode:
            if redis_phonecode.decode() != phonecode:
                return JsonResponse({'errno':400,'errmsg':'短信验证码错误'})
        else:
            return JsonResponse({'errno': 400, 'errmsg': '短信验证码已经失效'})


        if User.objects.filter(mobile=mobile):
            return JsonResponse({'errno': 400, 'errmsg': '该手机号已被注册'})

        # 用户注册
        try:
            user = User.objects.create_user(username=mobile,mobile=mobile,password=password)
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '注册用户失败'})

        usr = User.objects.get(mobile=mobile)
        usr.avatar = "default_avatar"
        usr.save()
        # 用户登陆
        login(request,user)

        return JsonResponse({'errno': 0, 'errmsg': '注册用户成功'})

# 登录用户
class LoginView(View):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        mobile=json_dict.get('mobile')
        password = json_dict.get('password')

        if not all([mobile,password]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少参数'})

        user = authenticate(request, username=mobile, password=password)
        if user is None:
            return JsonResponse({'errno': 400, 'errmsg': '用户名或密码错误'})

        login(request,user)
        return JsonResponse({'errno':0,'errmsg':'登陆成功'})

    # 获取登录状态
    def get(self,request):
        user = request.user
        if user.is_authenticated:
            # print({'errno':0,'errmsg':'已登录','data':{'name':user.username,'user_id':user.id}})
            return JsonResponse({'errno':0,'errmsg':'已登录','data':{'name':user.username,'user_id':user.id}})
        else:
            return JsonResponse({'errno': 4101, 'errmsg': '未登录'})

    # 退出登录
    def delete(self,request):
        logout(request)
        return JsonResponse({'errno': 0, 'errmsg': '已登出'})

# 用户中心
class self_center_view(View):
    def get(self, request):
        user = request.user
        # 1: 提取参数
        # 2：校验参数
        # 3：数据处理---查询信息，返回响应
        user_data = User.objects.get(pk=user.id)
        data = user_data.to_basic_dict()

        return JsonResponse({
            "errno": 0,
            "errmsg": "ok",
            "data": data,
        })


# 用户实名认证
class UserIdentityAuthView(LoginRequiredJSONMixin, View):
    def post(self,request):
        # 获取用户登陆
        user = request.user

        # 提取参数
        date = json.loads(request.body.decode())
        # 校验参数
        real_name = date.get('real_name')
        id_card	= date.get('id_card')

        # 必要性校验
        if not all([real_name,id_card]):
            return JsonResponse({
                'errno':400,
                'errmsg':'缺少必要性参数，请重新输入'
            },status=400)

        # 实名认证，姓名格式校验
        if not re.match('^[\u4e00-\u9fa5]{2,4}$',real_name):
            return JsonResponse({
                'errno':400,
                'errmsg':'实名格式有误，请重新输入'
            },status=400)

        # 身份证格式校验
        if not re.match('^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',id_card):
            return JsonResponse({
                'errno':400,
                'errmsg':'身份证格式有误，请重新输入'
            },status=400)

        # 2 数据处理，更新用户实名认证信息
        try:
            user.id_card = id_card
            user.real_name = real_name
            user.save()
        except Exception as e:
            return JsonResponse({'errno':400,'errmsg':'数据库写入失败'})

        return JsonResponse({'errno':0,'errmsg':'认证信息保存成功'})

    def get(self, request):
        user = request.user
        real_name = user.real_name
        id_card = user.id_card

        if not all([real_name, id_card]):
            return JsonResponse({
                "errno": 400,
                "errmsg": "用户未实名认证"
            })

        return JsonResponse({
            "errno": 0,
            "errmsg": "ok",
            "data": {
                "real_name": real_name,
                "id_card": id_card
            }
        })

# 上传用户头像
class set_user_avatar_View(LoginRequiredJSONMixin, View):

    def post(self, request):

        user = request.user
        # 1:提取参数
        image_file = request.FILES.get('avatar', None)

        # 2:校验参数
        if image_file is None:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        # 3:数据处理---读取数据(二进制)，上传到七牛云，将返回的地址，保存到数据库
        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片上传失败"
            })

        try:
            User.objects.filter(pk=user.id).update(avatar=file_name)

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })
        avatar_url = constants.QINIU_DOMIN_PREFIX + file_name
        # avatar_url = "http://qglpphun0.hn-bkt.clouddn.com/" + file_name
        # 4:构建响应
        return JsonResponse({
            "errno": 0,
            "errmsg": "ok",
            "data": {"avatar_url": avatar_url},
        })

# 我的房屋列表
class MyHouses(LoginRequiredJSONMixin,View):
    def get(self, request):
        houses_dict = House.objects.filter(user=request.user.id).order_by('-create_time')
        houses = []
        for house in houses_dict:
            houses.append({
                'house_id':house.id,
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time,
                "img_url": constants.QINIU_DOMIN_PREFIX + house.index_image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": house.user.avatar.url
            })

        return JsonResponse({
            "errno": 0,
            "errmsg": "ok",
            "data": {
                "houses": houses
            }
        })

# 用户名修改
class RenameView(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')

        # 参数校验
        if not name:
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})
        # 修改用户名
        user = request.user
        user.username = name
        user.save()
        return JsonResponse({'errno': '0',
                             'errmsg': 'OJBK'})